package com.yyplatform.admin.infra.utils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.assertj.core.util.Sets;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.yyplatform.admin.infra.exception.ErrorCode;
import com.yyplatform.admin.infra.exception.ServiceException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonUtils {

    public static String toJsonString(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("json processiong excetion", e);
            throw ServiceException.of(ErrorCode.INTERNAL_SERVER_ERROR);
        }
    }


    public static <T> Map<String, String> toJsonStringMap(String json) {
        try {
            Map<String, String> result;
            ObjectMapper mapper;
            TypeFactory factory;
            MapType type;

            factory = TypeFactory.defaultInstance();
            type = factory.constructMapType(HashMap.class, String.class, String.class);
            mapper = new ObjectMapper();
            return mapper.readValue(json, type);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

    }

    public static Set<String> toJsonStringSet(String json) {
        try {
            List<String> list = toJsonStringList(json);
            return new HashSet<>(list);
        } catch (Exception ex) {
            return Sets.newHashSet();
        }
    }

    public static List<String> toJsonStringList(String jsonArr) {
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            return objectMapper.readValue(jsonArr,
                    objectMapper.getTypeFactory().constructCollectionType(List.class, String.class));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }


    }


}
